//
//  NDHomeView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/4.
//】

import SwiftUI
import SwiftUIIntrospect

struct NDHomeView: View {
    @StateObject private var viewModel = NDHomeViewModel()
    @State private var isPresented = false
    @Environment(\.navigationManager) var navManager
    @StateObject private var refreshController = NDScrollViewRefreshController()
    @State private var showLocationAlert = false
    @State private var showRepaymentAlert = false
    
    private let toolModels: [NDHomeToolModel] = [
        NDHomeToolModel(title: "customer service",
                  normalIcon: "customer service"),
        NDHomeToolModel(title: "Product \nadvantages",
                  normalIcon: "Product  advantages"),
        NDHomeToolModel(title: "Loan \norder",
                  normalIcon: "Loan  order"),
        NDHomeToolModel(title: "Identity \nAuthentication",
                  normalIcon: "Identity  Authentication")
    ]
    
    var repaymentButtons: [NDPopupButton] {
        if let currentPetitor = viewModel.currentPetitor,
           let musicen = currentPetitor.musicen {
            
            // 根据 musicen 的数量创建对应数量的按钮
            return musicen.enumerated().map { index, item in
                NDPopupButton(item.atious ?? "", style: index == 0 ? .default : .underline) {
                    showRepaymentAlert = false
                    
                    if let schemeLink = item.trigesim,
                       !schemeLink.isEmpty {
                        if schemeLink.hasPrefix("http") || schemeLink.hasPrefix("https") {
                            goToWebView(schemeLink)
                        } else {
                            NDSchemeManager.shared.handleURL(schemeLink)
                        }
                    }
                }
            }
        }
        return []
    }
    
    var body: some View {
        let baseConfig = NDBaseConfig(
            backgroundImgName: "homesign up background1",
            backgroundColor: .clear,
            showNavigationBar: false,
            hiddenTabbar: false
        )
        let navigationConfig = NavigationConfig(
            title: "Home",
            showSystemBackButton: false
        )
        
        let locationButtons: [NDPopupButton] = [
            NDPopupButton.init(localizedString("Open setting")) {
                showLocationAlert = false
                UIApplication.shared.openAppSettings()
            },
            NDPopupButton.init(localizedString("Cancel"), style: .underline) {
                showLocationAlert = false
            }
        ]
        
        NDBaseContentView(
            baseConfig: baseConfig,
            navigationConfig: navigationConfig
        ) {
            ZStack {
                NDRefreshableScrollView(
                    refreshController: refreshController,
                    onRefresh: {
                        viewModel.loadHomeData()
                    }
                ) {
                    // 内容放在上层
                    ScrollView {
                        VStack(spacing: 20) {
                            // 顶部视图始终显示
                            NDHomeTopView(viewModel: viewModel,
                                          isLoading: viewModel.isLoading,
                                          onTapClosure: { productCard in
                                if let productId = productCard.selenify {
                                    beginApplying(productId: productId)
                                }
                            })
                            .padding(.horizontal, 5)
                            
                            // 如果有 smallCardModel 数据，显示列表样式
                            if let _ = viewModel.smallCardModel,
                                let productListModel = viewModel.productListModel {
                                let repayItems = viewModel.repaymentModel?.repayItems ?? []
                                smallCardContentView(smallCardModel: productListModel,
                                                     repayItems: repayItems)
                            }

                            // 只有有 largeCardModel 数据时才显示图片
                            if let _ = viewModel.largeCardModel {
                                largeCardContentView
                            }
                        }
                        .frame(maxHeight: .infinity)
                        .padding(.bottom, 5)
                    }
                    .padding(.bottom, 2)
                }
            }
        }
        .onAppear {
            refreshController.beginRefreshing()

            if viewModel.homeListData == nil {
                if NDUserDefaults.shared.retrieveBoolean(for: NDMarketKey) == nil {
                    NDEventAnallyticsTool.uploadMarketEvent()
                    NDUserDefaults.shared.saveBoolean(true, for: NDMarketKey)
                }
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    NDLocationManager.shared.requestLocationPermission()
                }
                
                NDKeychainTool.shared.saveString(DeviceIdentifier.vendorIdentifier, forKey: NDIdfvKey)
            }
        }
        .onChange(of: viewModel.isLoading) { isLoading in

            DispatchQueue.main.async {
                if isLoading {
                    NDProgressHUD.show()
                } else {
                    NDProgressHUD.dismiss()
                    refreshController.endRefreshing()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        // 强制滚动到顶部
                        if let scrollView = findScrollView() {
                            scrollView.setContentOffset(.zero, animated: false)
                        }
                    }
                }
            }
        }
        .onChange(of: viewModel.errorMessage) { msg in
            NDProgressHUD.showInfo(msg)
        }
        .onReceive(NotificationCenter.default.publisher(for: .schemeSwitchTab)) { notification in
            if let tabIndex = notification.userInfo?[NDSchemeKeys.tabIndex] as? Int {
                switchToTab(index: tabIndex)
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .schemeShowProductDetail)) { notification in
            if let productId = notification.userInfo?[NDSchemeKeys.productId] as? Int {
                goToProductDetailView(productId)
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .schemeShowLogin)) { _ in
            NotificationCenter.default.post(name: .logoutNotification, object: nil)
        }
//        .onReceive(NotificationCenter.default.publisher(for: .schemeRefreshHome)) { _ in
//            refreshController.beginRefreshing()
//        }
        .onReceive(NotificationCenter.default.publisher(for: .showLocationAlertNotification)) { notification in
            showLocationAlert = true
        }
        .ndAlertOnWindow(isPresented: $showLocationAlert,
                         title: "",
                         tips: nil,
                         message: localizedString("NSLocationWhenInUseUsageDescription"),
                         backgroundImage: "common_alert_bg",
                         buttons: locationButtons)
        .ndAlertOnWindow(isPresented: $showRepaymentAlert,
                         title: viewModel.currentPetitor?.pitister ?? "",
                         tips: nil,
                         message: viewModel.currentPetitor?.clositious ?? "",
                         backgroundImage: "common_alert_bg",
                         buttons: repaymentButtons)
    }
    
    func beginApplying(productId: Int)  {
        NDProgressHUD.show()
        NDLocationManager.shared.requestLocationPermission { allow in
            if WJAppEnvironment.shared.currentCountry == .indonesia {
                guard allow else {
                    NDProgressHUD.dismiss()
                    return
                }
            }
            
            requestApplyingInfo(productId: productId)
            
            NDLocationManager.shared.getCurrentLocation { result in
                switch result {
                case .success(let lctInfo):
                    NDEventAnallyticsTool.uploadLocationEvent(locationInfo: lctInfo)
                case .failure(_):
                    break
                }
            }
            
            NDEventAnallyticsTool.uploadTheDeviceDetailInformationEvent()
            
            if let startTime = NDUserDefaults.shared.retrieveInteger(for: NDloginStartTimeKey),
               let endTime = NDUserDefaults.shared.retrieveInteger(for: NDloginEndTimeKey) {
                NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .loginIn,
                                                         productId: nil,
                                                         orderNum: nil,
                                                         startTimeStamp: startTime,
                                                         endTimeStamp: endTime)
            }
        }
    }
    
    func requestApplyingInfo(productId: Int) {
        NDRequestManager.requestProductApplying(productId: productId) { applyingModel, msg, error in
            if error == nil {
                if let petitor = applyingModel?.petitor {
                    viewModel.currentPetitor = petitor
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        showRepaymentAlert = true
                    }
                } else if let schemeLink = applyingModel?.trigesim,
                          !schemeLink.isEmpty {
                    if schemeLink.hasPrefix("http") || schemeLink.hasPrefix("https") {
                        goToWebView(schemeLink)
                    } else {
                        NDSchemeManager.shared.handleURL(schemeLink)
                    }
                } else {
                    goToProductDetailView(productId)
                }
                
                NDProgressHUD.dismiss()
            } else {
                NDProgressHUD.showInfo(msg)
            }
        }
    }
}

extension NDHomeView {
    var largeCardContentView: some View {
        Group {
            if WJAppEnvironment.shared.currentCountry == .india {
                toolItemContentView
                    .padding(.horizontal, 16)
                Image("home_loan_tips")
                    .resizable()
                    .scaledToFill()
                    .padding(.horizontal, 16)
                    .padding(.bottom, 50)
            } else {
                Image("home_tips_id")
                    .resizable()
                    .scaledToFill()
                    .padding(.horizontal, 16)
                    .padding(.bottom, 50)
            }
        }
    }
    
    var toolItemContentView: some View {
        // 自定义TabBar
        HStack(spacing: 0) {
            ForEach(0..<toolModels.count, id: \.self) { index in
                NDHomeToolItem(model: toolModels[index])
                    .multilineTextAlignment(.center)
                    .frame(maxWidth: .infinity)
                    .frame(height: 112)
                    .frame(maxWidth: .infinity)
                    .frame(height: 112)
                    .onTapGesture {
                        clickToolItem(index)
                    }
            }
        }
    }
}

extension NDHomeView {
    func smallCardContentView(smallCardModel: PachistItem, repayItems: [RepayItem]) -> some View {
        Group {
            if !repayItems.isEmpty {
                
                NDInfiniteCarouselView(
                    repayItems,
                    autoScrollInterval: 3.0,
                    showsIndicators: false
                ) { repayItem in
                    NDRepaymentView(repayItem: repayItem)
                } onItemTapped: { repayItem in
                    print("点击轮播图：\(repayItem.trigesim ?? "")")
                    if let schemeLink = repayItem.trigesim,
                       !schemeLink.isEmpty {
                        if schemeLink.hasPrefix("http") || schemeLink.hasPrefix("https") {
                            goToWebView(schemeLink)
                        } else {
                            NDSchemeManager.shared.handleURL(schemeLink)
                        }
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 62)
                .background(
                    Color(hex: "#FF9068")
                        .cornerRadius(10)
                )
                .padding(.horizontal, 24)
            }
            
            NDSmallCardListView(smallCardModel: smallCardModel) { product in
                if let productId = product.selenify {
                    beginApplying(productId: productId)
                }
            }
        }
    }
    
    private func findScrollView() -> UIScrollView? {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let window = windowScene.windows.first else { return nil }
        
        func findScrollView(in view: UIView) -> UIScrollView? {
            if let scrollView = view as? UIScrollView {
                return scrollView
            }
            for subview in view.subviews {
                if let scrollView = findScrollView(in: subview) {
                    return scrollView
                }
            }
            return nil
        }
        
        return findScrollView(in: window)
    }
}

extension NDHomeView {
    func goToProductDetailView(_ productId : Int) {
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDProductDetailView(productId: productId)
        }
    }
    
    func clickToolItem(_ index: Int) {
        switch index {
        case 0:
            let url = NDAPIDomain.h5.rawValue + "citel"
            goToWebView(url)
        case 1:
            goToProductAd()
        case 2:
            switchToTab(index: 1)
        case 3:
            if let productId = viewModel.productCard?.selenify {
                beginApplying(productId: productId)
            }
        default:
            break
        }
    }
    
    func goToProductAd() {
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDProductAdvantages()
        }
    }
    
    func switchToTab(index: Int) {
        NotificationCenter.default.post(
            name: .switchTab,
            object: nil,
            userInfo: [TabSwitchKeys.tabIndex: index]
        )
    }
    
    func goToWebView(_ urlString: String) {
        let webUrlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        print("webUrlStr: \(webUrlStr ?? "")")
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDWebView(urlString: webUrlStr,
                      isFollowOrder: false,
                      isPresent: false)
        }
    }
}
